# -*- coding:utf-8 -*-
import json
import sys

from qdarkstyle import LightPalette, DarkPalette

from common.db import Record, session
from common.import_pyside import *
from common.data import DB
from record.components.configSetting import ConfigSettingWindow
from record.components.cus_signal import CusSignal

from record.components.popup import PopupWindow
from record.components.record_step import RecordStepWindow
from record.get_from_mouse_keybord.index import Cord
from record.views.main import Main
from record.views.runlog import RunLog
from record.views.side import Side
from utils.create_dir import create_case_dir
from utils.read_ini import read_ini
from utils.read_write_case import write_case
from utils.sendMsg import sendWinMsg

import qdarkstyle


class MainWin(QWidget):
    action_Update = CusSignal.actionUpdate

    def __init__(self):
        super(MainWin, self).__init__(parent=None)
        self.setWindowTitle("ToTest")
        self.setWindowIcon(QIcon('./icon/system.ico'))
        self.resize(1600, 800)
        self.setTheme()
        self.action_Update.connect(self.set_action_hide_show)

        main_layout = QHBoxLayout()
        main_splitter = QSplitter(Qt.Orientation.Horizontal)
        # main_splitter.setStyleSheet("QSplitter::handle {width:5px;background-color: #c0c0c0;border: 1px solid #c0c0c0;}")
        main_splitter.setStyleSheet("QSplitter {background-color: transparent}")
        self.sideWindow = Side(self)
        self.mainWindow = Main(self)
        self.runLogWindow = RunLog(self)
        main_splitter.addWidget(self.sideWindow)
        main_splitter.addWidget(self.mainWindow)
        main_splitter.addWidget(self.runLogWindow)
        main_layout.addWidget(main_splitter)
        self.setLayout(main_layout)

        # 关闭所有窗口时，不关闭系统
        QApplication.setQuitOnLastWindowClosed(False)

        # 系统图标
        self.tray = QSystemTrayIcon()
        self.tray.setIcon(QIcon('./icon/system.ico'))
        self.tray.setVisible(True)

        # 单击图标事件处理
        self.tray.activated.connect(self.SystemTrayIconClick)

        # 添加菜单项
        self._hide_action = QAction("隐藏窗口", self)
        self._hide_action.setIcon(QIcon('./icon/hide.ico'))
        self._hide_action.triggered.connect(self._hide_action_click)

        self._show_action = QAction("显示窗口", self)
        self._show_action.setIcon(QIcon('./icon/show.ico'))
        self._show_action.setVisible(False)
        self._show_action.triggered.connect(self._show_action_click)

        self._start_record_action = QAction("开始录制", self)
        self._start_record_action.setIcon(QIcon('./icon/start_record.ico'))
        self._start_record_action.triggered.connect(self._start_record_action_click)

        self._pause_action = QAction("暂停录制", self)
        self._pause_action.setIcon(QIcon('./icon/recording.ico'))
        self._pause_action.setVisible(False)
        self._pause_action.triggered.connect(self._pause_action_click)

        self._continue_record_action = QAction("继续录制", self)
        self._continue_record_action.setIcon(QIcon('./icon/start_record.ico'))
        self._continue_record_action.setVisible(False)
        self._continue_record_action.triggered.connect(self._continue_record_action_click)

        self._stop_record_action = QAction("停止录制", self)
        self._stop_record_action.setIcon(QIcon('./icon/stop_record.ico'))
        self._stop_record_action.setVisible(False)
        self._stop_record_action.triggered.connect(self._stop_record_action_click)

        self._config_action = QAction("配置设置", self)
        self._config_action.setIcon(QIcon('./icon/setting.ico'))
        self._config_action.setVisible(True)
        self._config_action.triggered.connect(self._config_action_click)

        self._remote_action = QAction("开启远程连接", self)
        self._remote_action.setIcon(QIcon('./icon/start_record.ico'))
        self._remote_action.setVisible(True)
        self._remote_action.triggered.connect(self._config_action_click)

        self._stop_remote_action = QAction("停止远程连接", self)
        self._stop_remote_action.setIcon(QIcon('./icon/stop_record.ico'))
        self._stop_remote_action.setVisible(True)
        self._stop_remote_action.triggered.connect(self._config_action_click)

        self._quit_action = QAction("退出", self)
        self._quit_action.setIcon(QIcon('./icon/shutdown.ico'))
        app_instance = QApplication.instance()
        self._quit_action.triggered.connect(app_instance.quit)

        self._tray_icon_menu = QMenu()
        self._tray_icon_menu.addAction(self._hide_action)
        self._tray_icon_menu.addAction(self._show_action)
        self._tray_icon_menu.addSeparator()
        self._tray_icon_menu.addAction(self._start_record_action)
        self._tray_icon_menu.addAction(self._pause_action)
        self._tray_icon_menu.addAction(self._continue_record_action)
        self._tray_icon_menu.addAction(self._stop_record_action)
        self._tray_icon_menu.addSeparator()
        self._tray_icon_menu.addAction(self._config_action)
        self._tray_icon_menu.addSeparator()
        self._tray_icon_menu.addAction(self._remote_action)
        self._tray_icon_menu.addAction(self._stop_remote_action)
        self._tray_icon_menu.addSeparator()
        self._tray_icon_menu.addAction(self._quit_action)

        self.tray.setContextMenu(self._tray_icon_menu)

    def SystemTrayIconClick(self, *args, **kwargs):

        action = str(*args).split('.')[-1]
        print("TrayIconClick:" + action)

        if action == 'DoubleClick':
            # 双击
            self._show_action_click()

        if action == 'Trigger':
            # 按下左键
            pass

        if action == 'Context':
            # 按下右键
            pass

        if action == 'MiddleClick':
            # 按下中键
            pass

    def setTheme(self):
        if read_ini("theme", "palette") == "light":
            self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api="pyside2", palette=LightPalette) + 'QGroupBox::title{margin-top: 5px;}')
        if read_ini("theme", "palette") == "dark":
            self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api="pyside2", palette=DarkPalette) + 'QGroupBox::title{margin-top: 5px;}')

    def _hide_action_click(self):
        self._hide_action.setVisible(False)
        self._show_action.setVisible(True)
        self.hide()

    def _show_action_click(self):
        self._show_action.setVisible(False)
        self._hide_action.setVisible(True)
        self.show()

    def _start_record_action_click(self):

        # 打开任务名称输入框
        PopupWindow().exec_()

        # 准备录制数据
        DB.start_record()

        # 打开录制记录框
        self.record_step_window = RecordStepWindow()
        self.record_step_window.show()

        # 调用录制事件
        Cord.start_record()

        # 发送开始录制的消息
        sendWinMsg("通知", "录制开始！！")

        # 更该actions
        DB.actions_status = DB.actions_status | {"pause_action": True, "stop_record_action": True,
                                                 "start_record_action": False}
        self.action_Update.emit()

    def _pause_action_click(self):
        # 暂停录制
        Cord.pause_record()

        # 更该actions
        DB.actions_status = DB.actions_status | {"pause_action": False, "continue_record_action": True}
        self.action_Update.emit()

    def _continue_record_action_click(self):
        # 继续录制
        Cord.continue_record()

        # 更该actions
        DB.actions_status = DB.actions_status | {"pause_action": True, "continue_record_action": False}
        self.action_Update.emit()

    def _stop_record_action_click(self):

        # 停止录制
        Cord.stop_record()
        # 写入录制数据（持久化）
        DB.stop_record()
        # 存储
        instance = session.query(Record).filter(Record.case_name == DB.case_task_name).first()
        instance.case_data = json.dumps(DB.caseData)
        session.commit()
        # 关闭录制记录框
        self.record_step_window.close()
        # 发送关闭录制的消息
        sendWinMsg("通知", "录制结束！！")

        # 更该actions
        DB.actions_status = DB.actions_status | {"pause_action": False, "continue_record_action": False,
                                                 "stop_record_action": False, "start_record_action": True}
        self.action_Update.emit()

    def _config_action_click(self):
        self.config_window = ConfigSettingWindow()
        self.config_window.show()

    def showEvent(self, event) -> None:
        self.action_Update.emit()

    # 关闭窗口事件
    def closeEvent(self, event):
        # 更该actions
        DB.actions_status = DB.actions_status | {"show_action": True, "hide_action": False}
        self.action_Update.emit()

    def set_action_hide_show(self):
        self._hide_action.setVisible(DB.actions_status["hide_action"])
        self._show_action.setVisible(DB.actions_status["show_action"])
        self._start_record_action.setVisible(DB.actions_status["start_record_action"])
        self._pause_action.setVisible(DB.actions_status["pause_action"])
        self._continue_record_action.setVisible(DB.actions_status["continue_record_action"])
        self._stop_record_action.setVisible(DB.actions_status["stop_record_action"])
        self._config_action.setVisible(DB.actions_status["config_action"])
        self._remote_action.setVisible(DB.actions_status["remote_action"])
        self._stop_remote_action.setVisible(DB.actions_status["stop_remote_action"])
        self._quit_action.setVisible(DB.actions_status["quit_action"])


def run_main_window():
    app = QApplication()
    win = MainWin()
    win.show()
    sys.exit(app.exec_())
